package com.ruoyi;

import org.eclipse.paho.client.mqttv3.IMqttAsyncClient;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Author Alan Zhang
 * @Date 2025/3/12 10:10
 */

@Component
public class MqttClientCallBack implements MqttCallback {
    private static final Logger logger = LoggerFactory.getLogger(MqttClientCallBack.class);

    @Value("${spring.mqtt.client.id}")
    private String clientId;

    /**
     * 与服务器断开的回调
     */
    @Override
    public void connectionLost(Throwable cause) {
        logger.error(clientId + "与服务器断开连接！！" + cause.getMessage());
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        System.out.println(String.format("接收消息主题 : %s",topic));
        System.out.println(String.format("接收消息Qos : %d",mqttMessage.getQos()));
        System.out.println(String.format("接收消息内容 : %s",new String(mqttMessage.getPayload())));
        System.out.println(String.format("接收消息retained : %b",mqttMessage.isRetained()));
    }

    /**
     * 消息发布成功的回调
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        IMqttAsyncClient client = token.getClient();
        System.out.println(client.getClientId()+"发布消息成功！");

    }

}
